package com.roadjava.javaweb.student.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.roadjava.javaweb.student.beans.res.ResultDTO;
import com.roadjava.javaweb.student.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

@WebServlet(name = "testAjaxServlet",urlPatterns = "/testAjaxServlet")
public class TestAjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JSONObject paramObj = null;
        try(BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"))) {
            StringBuilder totalLine = new StringBuilder();
            String line;
            while ((line =br.readLine()) != null) {
                totalLine.append(line);
            }
            // 因为前端指定了contentType:"application/json",所以接受到的totalLine是json对象
            paramObj = JSON.parseObject(totalLine.toString());
        }catch (Exception e) {
            e.printStackTrace();
        }

//        String userName = request.getParameter("userName");
//        String webSite = request.getParameter("webSite");
        if (paramObj == null) {
            paramObj = new JSONObject();
        }
        String userName = paramObj.getString("userName");
        String webSite = paramObj.getString("webSite");
        System.out.println(userName);
        System.out.println(webSite);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg","收到了");
        ResponseUtil.respAppJson(response, ResultDTO.buildSuccess(jsonObject));

    }
}
